    /*  
    championBuilder - Champions Online character planner.
    Copyright (C) 2009 Moritz Hartmeier
    
    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.
    
    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.
    
    You can find the GNU General Public License in the data folder.
    */


package ch.zarzu.champions.builder.updater;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import ch.zarzu.champions.builder.App;
import ch.zarzu.champions.builder.ErrorLog;
import ch.zarzu.champions.builder.FileSystemWrapper;
import ch.zarzu.champions.builder.PrefLink;
import ch.zarzu.champions.builder.SystemLink;
import ch.zarzu.champions.builder.gui.MainInterface;
import ch.zarzu.util.AppPath;

public class AutoUpdater extends Thread {
	private MainInterface user_interface;
	private String app_path, download_link;
	final static int size=1024;
	private SystemLink sys_link;
	private PrefLink pref_link;
	
	public AutoUpdater () {
		user_interface = MainInterface.getInstance();
		sys_link = SystemLink.getInstance();
		pref_link = PrefLink.getInstance();
	}
	
	
	public void run() {
		try { 
			app_path = AppPath.get();
			
			URL url;
			if (App.DIST.equals("exe"))
		    	url = new URL("http://champions.zarzu.ch/autoupdate_after_0_4/log.txt");
			else if (App.DIST.equals("jar5") && !App.not_app)
                url = new URL("http://champions.zarzu.ch/autoupdate_after_0_4/log_jar5.txt");
            else
                url = new URL("http://champions.zarzu.ch/autoupdate_after_0_4/log_jar6.txt");
			
			InputStream is = url.openStream(); 
			InputStreamReader isr = new InputStreamReader(is); 
			BufferedReader br = new BufferedReader(isr); 
			
			String input = "";
			while (br.ready()) {
				input += br.readLine() + ","; 
			}
			br.close(); 
			is.close();
			isr.close();
			System.out.println("http://champions.zarzu.ch" + input.split("[,]")[1]);
			download_link = "http://champions.zarzu.ch" + input.split(",")[2];
			
			//current version of the program
			String cur_version = App.VERSION;

			if(!cur_version.equals(input.split("[,]")[0]) && App.DIST.equals("exe")) {
				url = new URL("http://champions.zarzu.ch" + input.split("[,]")[1]); 
				OutputStream os = null;
				URLConnection url_con = null;
				new File(app_path + "updates").mkdir();
				
				user_interface.setTopText(sys_link.translate("newer_version").replace("(1)", input.split("[,]")[0]), 0);
				try {
					sleep(2000);
				} catch (InterruptedException e) {}
				try {
					byte[] buf;
					int ByteRead,ByteWritten=0;
					os = new BufferedOutputStream(new FileOutputStream(app_path + "updates/new.zip"));
		
					url_con = url.openConnection();
					is = url_con.getInputStream();
					buf = new byte[size];
					Double percentage;
					while ((ByteRead = is.read(buf)) != -1) {
						os.write(buf, 0, ByteRead);
						ByteWritten += ByteRead;
						percentage = new Double(ByteWritten) / new Double(url_con.getContentLength()) * 100;
						user_interface.setTopText(sys_link.translate("down_percentage").replace("(1)", Integer.toString(percentage.intValue())), 0);
					}
					os.close();
					
					//lock the top right feedback text and tell the user to click for updating
					user_interface.setTopText(sys_link.translate("click_update").replace("(1)", input.split("[,]")[0]), 1);
				} catch (Exception e) {
					//lock the top right feedback text and tell the user to click for downloading it
					//this is for when the automatic update failed to download and/or write
					user_interface.setTopText(sys_link.translate("click_download").replace("(1)", input.split("[,]")[0]), 2);
				}
			} else if(!cur_version.equals(input.split("[,]")[0])) {
				//lock the top right feedback text and tell the user to click for downloading it
				//this is for when the automatic update failed to download and/or write
				user_interface.setTopText(sys_link.translate("click_download").replace("(1)", input.split("[,]")[0]), 2);
			}
		} catch (MalformedURLException e) {
		    ErrorLog.v("autoupdater", e);
			e.printStackTrace();
		} catch (IOException e) {
		    ErrorLog.v("autoupdater", e);
			e.printStackTrace();
		}
	}
	
	public String getDownloadLink() {
		return download_link;
	}
}
